package com.example.orderservice.service;

import com.example.orderservice.event.OrderEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

/**
 * 订单事件发布服务
 * 负责将订单事件发布到RocketMQ
 */
@Slf4j
@Service
public class OrderEventPublisher {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    private static final String ORDER_TOPIC = "ORDER_EVENTS";

    /**
     * 发布订单事件到RocketMQ
     */
    public void publishOrderEvent(OrderEvent event) {
        try {
            // 将事件转换为JSON字符串
            String eventJson = objectMapper.writeValueAsString(event);
            
            // 发布到RocketMQ
            rocketMQTemplate.syncSend(
                ORDER_TOPIC + ":" + event.getEventType(),
                MessageBuilder.withPayload(eventJson).build()
            );
            
            log.info("订单事件发布成功 - 事件类型: {}, 订单ID: {}, 事件ID: {}", 
                event.getEventType(), event.getOrderId(), event.getEventId());
                
        } catch (Exception e) {
            log.error("发布订单事件失败 - 事件类型: {}, 订单ID: {}, 错误: {}", 
                event.getEventType(), event.getOrderId(), e.getMessage(), e);
            throw new RuntimeException("发布订单事件失败", e);
        }
    }
}

